﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common.PropertyMapper;
using Microsoft.Practices.ObjectBuilder2;
using Microsoft.Practices.Unity;

namespace Common.Unity.Extensions.PropertyMapping
{
	public class PropertyMappingCreatorPolicy : IObjectCreationPolicy
	{
		public Type TargetBuildType { get; set; }
		public string TargetBuildName { get; set; }

		public string Expression { get; set; }

		public object Create( IBuilderContext context )
		{
			var target = ResolveTarget( context );
			var evaluation = PropertyMappingExpression.Evaluate( target, Expression );
			var result = evaluation.Last.Value.Value;
			return result;
		}

		object ResolveTarget( IBuilderContext context )
		{
			var child = context.CloneForNewBuild( new NamedTypeBuildKey( TargetBuildType, TargetBuildName ), null );
			var result = child.Strategies.ExecuteBuildUp( child );
			return result;
		}

	}
}
